import React,{memo,useRef,useState,useEffect,useCallback} from "react";
import type {FC,ReactNode} from 'react'
import '@/assets/style/play.less'
import { formatTime } from "@/utils/formatTime";
import { useAppSelector, useAppDispatch, appShallowEqual } from "@/store/index";
import { incrementCurrentIndex,decrementCurrentIndex,removeSong } from "@/store/modules/music";
import {setBackGroundColor} from '@/utils/randomColor'
import { checkImageURL } from "@/utils/checkImg";
import { getPlayListInfoService,getSongCoverService,getSongLinkService,getLyricService } from "@/api/music";

import PlayList from "@/components/PlayList";
import SearchBar from "@/components/SearchBar";

// import '@/assets/style/play.less'
interface songDisplay{
  keyId:number,
  id:number,
  name:string,
  singerName:string,
  albumMid:string
}
interface lyric{
  time:number,
  txt:string
}

type cache={  
    songUrl:string,
    imgUrl:string,
    lyrics:lyric[]
}

interface cacheType {
  [key: string]:cache
}

interface IProps{
    children?:ReactNode
}

const Play: FC<IProps>=()=>{
  const player = useRef<HTMLAudioElement>(null);
  const bar = useRef<HTMLDivElement>(null);
  const progress = useRef<HTMLDivElement>(null);
  const lyricRef = useRef<HTMLDivElement>(null);
  const scrollRef = useRef<HTMLDivElement>(null);
  const titleRef= useRef<HTMLDivElement>(null);
  const pauseRef = useRef<HTMLDivElement>(null);
  const [currentTime, setCurrentTime] = useState<number>(0);
  const [duration, setDuration] = useState<number>(0);
  const [showList, setShowList] = useState<songDisplay[]>([]);
  const [currentLink, setCurrentLink] = useState<string>("");
  const [currentImg, setCurrentImg] = useState<string>("");
  const [currentLyric, setCurrentLyric] = useState<lyric[]>([]);
  const [lyricIndex, setLyricIndex] = useState<number>(0);
  const [title, setTitle] = useState<string>("");
  const [ifShowList, setIfShowList] = useState<boolean>(false);
  const [ifShowSearch, setIfShowSearch] = useState<boolean>(false);
  //skipLoad用于解决删除元素的id小于currentIndex时，当前播放歌曲刷新问题
  const [skipLoad, setSkipLoad] = useState<boolean>(false);
  //flag用来解决删除歌曲的id是否等于currentIndex问题
  const [flag, setFlag] = useState<boolean>(false);

  const currentLyricRef = useRef<lyric[]>([]);
  const lyricIndexRef = useRef<number>(0);
  const playListLengthRef = useRef<number>(0);
  //缓存提升性能
  const songCacheRef=useRef<cacheType>({})
  //标题定时器
  let timer:any=null
  

  const { currentIndex, playList } = useAppSelector(
    (state) => ({
      currentIndex: state.music.currentIndex,
      playList: state.music.playList,
    }),
    appShallowEqual
  );

  const dispatch = useAppDispatch();
  
    


  const getPlayListInfo = async () => {
    //获取之前的列表信息
     
    const data = (await getPlayListInfoService(playList)).data.data;
    const newData = data.map((e, index) => {
      e.id = index;
      e.keyId = index;
      return e;
    });
    console.log(newData);
    setShowList(newData);

    // 初次加载时执行 loadCurrentSong
    const item = playList[currentIndex];
    const ele = newData[currentIndex];

    if (item && item[0]){
       getSongLink(item[0]);
       getLyric(item[0]);
    }
    if (ele){
       getSongCover(ele.albumMid);
    }
      
      setTitle(`${ele.name} - ${ele.singerName}`);
    setBackGroundColor();
  };

  const getSongLink = async (mid: string) => {
    const cacheSong = songCacheRef.current[mid];
    if (cacheSong && cacheSong.songUrl) {
      const link = cacheSong.songUrl;
     setCurrentLink(link)
      return;
    }

    try{
      const res = (await getSongLinkService(mid)).data;
    if (!res) {
      throw new Error("Can not get songLink resource!");
    }
    const linkUrl = res.data.playUrl[mid].url;
    setCurrentLink(linkUrl);

    songCacheRef.current = {
      ...songCacheRef.current,
      [mid]: {
        songUrl: linkUrl,
        imgUrl: "",
        lyrics: [],
      },
    };

    }catch(error){
      console.error("获取播放链接失败:", error);
    }

    
    
  };

  const getSongCover = async (mid: string) => {
    const cacheSong = songCacheRef.current[mid];
    if (cacheSong && cacheSong.imgUrl) {
      const img = cacheSong.imgUrl;
      
      setCurrentImg(img)
      return;
    }
    try {
      const res = (await getSongCoverService(mid)).data;

      if (
        !res ||
        !res.response ||
        !res.response.data ||
        !res.response.data.imageUrl
      ) {
        throw new Error("封面数据为空");
      }
      checkImageURL(res.response.data.imageUrl)
      .then(isValid=>{
        if(!isValid) throw new Error("封面链接无效");
      });
      const imgUrl = res.response.data.imageUrl;
      setCurrentImg(imgUrl);

      const currentCache = songCacheRef.current[mid];
      if(currentCache){
        (songCacheRef.current[mid] as any).imgUrl=imgUrl
      }
      

    } catch (error) {
      console.error("获取封面失败:", error);
      setCurrentImg("/T002R500x500M000002qyIry4Y11h1.webp"); // 默认图片路径根据项目配置调整
    }

    
  };

  const getLyric = async (mid: string) => {
    //清除空白提示
    // const ele = lyricRef.current;
    // if (ele) {
    //   ele.innerHTML ='';
    // }
    //先从缓存区读取
    const cacheSong=songCacheRef.current[mid]
    if (cacheSong && Object.is(cacheSong.lyrics,[])) {
      console.log(444);
      const lyric = cacheSong.lyrics;
      console.log(lyric);
      setCurrentLyric(lyric);
      return;
    }
    try {
      const res = (await getLyricService(mid, true)).data;

      if (
        !res ||
        !res.response ||
        !res.response.lyric ||
        !res.response.lyric.lines
      ) {
        throw new Error("歌词数据为空");
      }

      const lyric = res.response.lyric.lines;
      console.log(lyric);
      setCurrentLyric(lyric);

       const currentCache = songCacheRef.current[mid];
       if (currentCache) {
         (songCacheRef.current[mid] as any).lyrics = lyric;
       }

    } catch (error) {
      console.error("获取歌词失败:", error);
      const ele = lyricRef.current
      if(ele){
        ele.innerHTML = "<div>列表暂无歌曲哦，快去添加吧</div>";
      }
    }
  };

  const loadCurrentSong = () => {
    const item = playList[currentIndex];
    const ele = showList[currentIndex];

    if (!item || !item[0]) return;
    getSongLink(item[0]);
    getLyric(item[0]);

    if (!ele) return;
    getSongCover(ele.albumMid);

    setTitle(`${ele.name} - ${ele.singerName}`);
    setBackGroundColor();
  };

  //监听currentIndex变化
  useEffect(() => {
    //必须对currentIndex进行判断，否则删除列表最后一个元素可能currentIndex会越界，与reducer配合控制currentIndex
    if (skipLoad) {
      setSkipLoad(false); // 重置标志
      return;
    }
    loadCurrentSong();
  }, [currentIndex, flag]);

  useEffect(() => {
    //第一次加载不显示背景问题
    setBackGroundColor();
    //获取并处理播放列表信息

    getPlayListInfo();
    //监听音乐播放时间
    const audio = player.current;
    const slide = bar.current;
    const duration = progress.current;
    if (!audio) return;
    if (!slide) return;
    if (!duration) return;

    const updateTime = () => {
      setCurrentTime(audio.currentTime);
      if (!audio.duration) {
        setDuration(0);
        return;
      }
      setDuration(audio.duration);

      const width = Math.floor((audio.currentTime / audio.duration) * 100);
      slide.style.width = `${width}%`;
      //  bar.style.width = `${width}%`;
    };

    const handleLoadedMetadata = () => {
      setDuration(audio.duration || 0);
    };

    const handleDrag = (e) => {
      const pos = (e.pageX - duration.offsetLeft) / duration.offsetWidth;
      audio.currentTime = pos * audio.duration;
      if (audio.paused) {
        audio.play();
        if (pauseRef.current) {
          pauseRef.current.classList.remove("bi-play-fill");
          pauseRef.current.classList.add("bi-pause-fill");
        }
      } 
    };


    const handlePlay = () => {
      if(!audio.paused){
        if (pauseRef.current) {
          pauseRef.current.classList.remove("bi-play-fill");
          pauseRef.current.classList.add("bi-pause-fill");
        }

      }
    };

    const handlePause = () => {
      if (audio.paused) {
        if (pauseRef.current) {
          pauseRef.current.classList.remove("bi-pause-fill");
          pauseRef.current.classList.add("bi-play-fill");
        }
      }
    };
    //开启标题循环播放
     timer = setInterval(ctrlTitleScroll, 30); 

     audio.addEventListener('play',handlePlay)
     audio.addEventListener('pause',handlePause)
    duration.addEventListener("click", handleDrag);
    audio.addEventListener("timeupdate", updateTime);
    audio.addEventListener("timeupdate", updateCurrentLyric);
    audio.addEventListener("loadedmetadata", handleLoadedMetadata);
    audio.addEventListener("ended", handleEnded);
    // 清理副作用
    return () => {
      audio.removeEventListener("play", handlePlay);
      audio.removeEventListener("pause", handlePause);
      audio.removeEventListener("timeupdate", updateTime);
      audio.removeEventListener("loadedmetadata", handleLoadedMetadata);
      audio.removeEventListener("timeupdate", updateCurrentLyric);
      duration.removeEventListener("click", handleDrag);
      audio.removeEventListener("ended", handleEnded);
     clearInterval(timer)
     //存储上一次的播放列表
     
    };
  }, []);

  // //监听currentIndex
  // useEffect(()=>{
  //   //加载新的链接
  //   loadCurrentSong()
  // },[currentIndex])

  //监听链接是否加载完毕
  useEffect(() => {
    if (currentLink && player.current) {
      player.current.play().catch((err) => {
        console.error("播放失败:", err);
      });
    }
  }, [currentLink]);

  //监听playList的删增
  const getSingleSongData = async (data) => {
    try {
      const resData = (await getPlayListInfoService(data)).data.data[0];
      if (!resData) throw new Error("获取歌曲信息失败");

      // 给新项一个准确的 id / keyId
      const newId = showList.length;
      const newItem: songDisplay = {
        ...resData,
        id: newId,
        keyId: newId,
      };

      // 同步更新 showList
      setShowList((prev) => [...prev, newItem]);

      // 如果列表之前空了，就加载它
      if (showList.length === 0) {
        getSongCover(newItem.albumMid);
        setTitle(`${newItem.name} - ${newItem.singerName}`);
        setBackGroundColor();
      }
    } catch (err) {
      console.error(err);
    }
  };
  // const getSingleSongData = async (data) => {
  //   try{
  //     const res = (await getPlayListInfoService(data)).data.data[0];
  //     if(!res) throw new Error('获取歌曲信息失败')
  //   const nextItem = showList[showList.length - 1];
  //   if (nextItem) {
  //     res.id = nextItem.id + 1;
  //     res.keyId = nextItem.keyId + 1;
  //   }
  //   setShowList([...showList, res]);

  //   //解决删除列表全部歌曲后，重新添加歌曲后不加载和播放问题
  //   if(showList.length===0){
  //      getSongCover(res.albumMid);
  //      setTitle(`${res.name} - ${res.singerName}`);
  //      setBackGroundColor();
  //   }
  //   }catch(err){
  //     console.error( err);
  //   }
  // };

  useEffect(() => {
    // 每当播放列表变化，就检查长度
    if (playList.length === 0) {
      // 1. 列表空了 → 清空播放器
      setCurrentLink("./11");
      setCurrentImg("/T002R500x500M000002qyIry4Y11h1.webp");
      setCurrentLyric([]);
      setLyricIndex(0);
      setTitle("");
      // 同时把 <audio> 停掉
      if (player.current) {
        player.current.pause();
        player.current.currentTime = 0;
      }
      // 清空歌词容器
      if (lyricRef.current) {
        lyricRef.current.innerHTML = "<div>列表暂无歌曲哦，快去添加吧~</div>";
      }
    }
    if (playList.length > showList.length) {
      const data = playList[playList.length - 1];
      getSingleSongData([data]);

      if(playList.length==1){
        // 添加下面两行：
        setSkipLoad(false); // 允许 loadCurrentSong 被触发
        setFlag((f) => !f); // 触发 currentIndex useEffect 的监听
      }
    }
    playListLengthRef.current = playList.length;
  }, [playList]);


  

  useEffect(() => {
    initLyric();
  }, [currentLyric]);

  //监听currentLyric和currentLyric的变化来更新ref
  useEffect(() => {
    currentLyricRef.current = currentLyric;
  }, [currentLyric]);

  useEffect(() => {
    lyricIndexRef.current = lyricIndex;
  }, [lyricIndex]);

  
  const playPreSong = () => {
    dispatch(decrementCurrentIndex());
  };

  const playNextSong = () => {

    dispatch(incrementCurrentIndex());
  };

  const handleEnded=()=>{
    if(playListLengthRef.current===1){
      const audio=player.current
      if(audio){
        audio.pause()
        if (pauseRef.current) {
          pauseRef.current.classList.remove("bi-pause-fill");
          pauseRef.current.classList.add("bi-play-fill");
        }
      }
      return
    }

    playNextSong()
  }

  const playSong = () => {
    if (!player.current) {
      throw new Error("Audio Element not found");
    }
    if (player.current.paused || player.current.ended) {
      player.current.play();
     if(!player.current.paused){
       if (pauseRef.current) {
         pauseRef.current.classList.remove("bi-play-fill");
         pauseRef.current.classList.add("bi-pause-fill");
       }
     }
    } else{
      player.current.pause();
      if(player.current.paused){
        if (pauseRef.current) {
          pauseRef.current.classList.remove("bi-pause-fill");
          pauseRef.current.classList.add("bi-play-fill");
        }
      }
    }
  };

  

  const handleListShow = () => {
    setIfShowList(!ifShowList);
  };

  const handleSearchShow = () => {
    setIfShowSearch(!ifShowSearch);
  };

  const handleDelete = (
    id: number,
    event: React.MouseEvent<HTMLSpanElement>
  ) => {
    event.stopPropagation();
    dispatch(removeSong(id));

    const newData = [...showList];
    newData.splice(id, 1);

    console.log(newData);

    setShowList(
      newData.map((e, index) => {
        e.id = index;
        return e;
      })
    );

    //解决当前播歌曲被删除还会继续播放问题
    if (id === currentIndex) {
      setFlag(!flag);
    }
    if (id < currentIndex) {
      setSkipLoad(true);
    }
  };

  //歌词渲染函数
  const initLyric = () => {
    const con = lyricRef.current;
    if (!con) return;
   
    con.innerHTML = "";
    con.style.transform = "translateY(0)";
    con.style.height = `${currentLyric.length * 30}px`;
    for (let i = 0; i < currentLyric.length; i++) {
      const item = document.createElement("div");
      const ly = currentLyric[i];
      if (!ly) return;
      
      item.innerText = ly.txt.replace(/&apos;/g,'\'');
      con.appendChild(item);
    }

    setLyricIndex(0);
  };

  const render = useCallback((index: number) => {
    const con = lyricRef.current;
    if (!con) {
      return;
    }
    const children = con.children;

    if (index > 0) {
      const item = children[index - 1];
      if (item) {
        item.classList.remove("current");
      }
    }
    const item = children[index];
    if (item) {
      item.classList.add("current");
    }

    if (index >= 2) {
      let moveY=0
      for(let i=0;i<index-1;i++){
        const ch=children[i]
        if(ch){
          moveY +=(ch as HTMLDivElement).offsetHeight;
        }
        
      }
      con.style.transform = `translateY(${-moveY}px)`;
    }
  }, []);

  const updateCurrentLyric = useCallback(() => {
    const audio = player.current;
    // 使用 ref 获取最新值
    const currentLyric = currentLyricRef.current;
    const currentIndex = lyricIndexRef.current;

    if (currentLyric.length === 0) {
      console.log(111);
      return;
    }

    if (!audio) {
      return;
    }

    const currentTime = audio.currentTime * 1000;
    let index = currentLyric.length - 1;

    for (let i = 0; i < currentLyric.length; i++) {
      const lyric = currentLyric[i];
      if (lyric && lyric.time > currentTime) {
        index = i - 1;
        break;
      }
    }

    // 边界情况处理
    if (index === -1) index = 0;

    // 只有当索引变化时才更新
    if (currentIndex === index) return;

    // 更新状态
    setLyricIndex(index);
    render(index);
  }, []);

  useEffect(() => {
    // ...其他代码...
    const audio = player.current;
    if (!audio) {
      return;
    }
    const updateHandler = updateCurrentLyric;
    audio.addEventListener("timeupdate", updateHandler);

    return () => {
      // ...其他清理...
      audio.removeEventListener("timeupdate", updateHandler);
    };
  }, [updateCurrentLyric]); // 添加依赖
  // const updateCurrentLyric = () => {
  //   const audio = player.current;
  //   if (currentLyric.length === 0) {
  //     console.log(111);
  //     return;
  //   }
  //   if (!audio || currentLyric.length === 0) {
  //     console.log(222);
  //     return;
  //   }
  //   const currentTime = audio.currentTime;
  //   let index = currentLyric.length - 1;
  //   for (let i = 0; i < currentLyric.length; i++) {
  //     const lyric = currentLyric[i];
  //     if (lyric && lyric.time > currentTime) {
  //       index = i - 1;
  //       break;
  //     }
  //   }

  //   if (lyricIndex === index || index === -1) return;
  //   setLyricIndex(index);
  //   render(index);
  // };


  //标题滚动函数
   const ctrlTitleScroll = () => {
     const con = titleRef.current;
     const scroll = scrollRef.current;
     if (!con || !scroll) return;

     // 获取当前 transform 值
     const style = window.getComputedStyle(scroll);

     const matrix = new WebKitCSSMatrix(style.transform);
     let currentX = matrix.m41;

     // 每次移动更多像素（比如：5px）

     const containerWidth = con.offsetWidth;
     const contentWidth = scroll.offsetWidth;

     currentX -= containerWidth*0.002;
     // 如果已经完全滚出左侧，则重置位置
     if (currentX + contentWidth <= 0) {
      
       currentX = containerWidth; // 瞬间跳回右边
     }

     scroll.style.transform = `translateX(${currentX}px)`;
   };

  return (
    <div className="container">
      <div className="content">
        <div className="img-container">
          <img src={currentImg} alt="" />
        </div>
        <div className="text">
          <div className="title" ref={titleRef}>
            <div className="scroll-bar" ref={scrollRef}>
              {title}
            </div>
          </div>
          <div className="lyric">
            <div className="lyric-list" ref={lyricRef}></div>
          </div>
        </div>
      </div>
      <audio src={currentLink} ref={player}></audio>
      <div className="ctrl-bar">
        <div className="duration" ref={progress}>
          <div className="bar" ref={bar}></div>
        </div>
        <div className="time">
          {formatTime(currentTime)}/{formatTime(duration)}
        </div>
        <div className="ctrl-btn">
          {/* <button onClick={playPreSong}>pre</button>
          <button onClick={playSong}>stop</button>
          <button onClick={playNextSong}>next</button> */}

          <div
            onClick={playPreSong}
            className="pre-btn bi-skip-backward-fill"
          ></div>
          <div
            onClick={playSong}
            className="pause-btn bi-play-fill"
            ref={pauseRef}
          ></div>
          <div
            onClick={playNextSong}
            className="next-btn bi-skip-forward-fill"
          ></div>
        </div>
      </div>
      <div
        className="show-list bi-music-note-list"
        onClick={handleListShow}
      ></div>
      <div className="search-btn bi-search" onClick={handleSearchShow}>
        
      </div>
      <PlayList
        ifShow={ifShowList}
        showList={showList}
        handleDelete={handleDelete}
      />
      <SearchBar ifShow={ifShowSearch} />
    </div>
  );
}

export default memo(Play)